package com.ruoyi.jihuo.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.jihuo.api.CallTaoApiService;
import com.ruoyi.jihuo.domain.JhTmAccount;
import com.ruoyi.jihuo.domain.search.JhTmAccountSearch;
import com.ruoyi.jihuo.mapper.JhTmAccountMapper;
import com.ruoyi.jihuo.service.IJhTmAccountService;
import com.ruoyi.system.service.ISysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 天猫账户Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-27
 */
@Service
public class JhTmAccountServiceImpl implements IJhTmAccountService {
    private static final Logger log = LoggerFactory.getLogger(JhTmAccountServiceImpl.class);
    @Autowired
    private JhTmAccountMapper jhTmAccountMapper;

    @Autowired
    private CallTaoApiService callTaoApiService;

    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询天猫账户
     *
     * @param jhId 天猫账户主键
     * @return 天猫账户
     */
    @Override
    public JhTmAccount selectJhTmAccountByJhId(Long jhId) {
        return jhTmAccountMapper.selectJhTmAccountByJhId(jhId);
    }

    /**
     * 查询天猫账户列表
     *
     * @param jhTmAccount 天猫账户
     * @return 天猫账户
     */
    @Override
    public List<JhTmAccount> selectJhTmAccountList(JhTmAccountSearch jhTmAccount) {
//        if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
            jhTmAccount.setJhUserId(SecurityUtils.getUserId());
//        }
        return jhTmAccountMapper.selectJhTmAccountList(jhTmAccount);
    }

    /**
     * 查询所有天猫账户列表
     *
     * @return 天猫账户
     */
    @Override
    public List<JhTmAccount> selectAllJhTmAccountList() {
        return jhTmAccountMapper.selectAllJhTmAccountList(SecurityUtils.getUserId());
    }

    /**
     * 新增天猫账户
     * appKey 与 appSecret 是接口商的，如果单接口商就是固定的，如果后续有多接口商再考虑修改
     *
     * @param jhTmAccount 天猫账户
     * @return 结果
     */
    @Override
    public int insertJhTmAccount(JhTmAccount jhTmAccount) {
        jhTmAccount.setJhUserId(SecurityUtils.getUserId());
        String feature = jhTmAccount.getJhFeature();
        String appKey = jhTmAccount.getJhAppKey();
        String appSecret = jhTmAccount.getJhAppSecret();
        if (StringUtils.isBlank(feature) &&
                StringUtils.isBlank(appKey) &&
                StringUtils.isBlank(appSecret)) {
            throw new ServiceException("appKey、appSecret、特征不能为空");
        }
            //appKey和appSecret保存到redis中，key为feature
            String redisKey = jhTmAccount.getJhFeature();
            JSONObject config = new JSONObject();
            config.put("appKey", appKey);
            config.put("appSecret", appSecret);
            redisCache.setCacheObject(redisKey, config.toJSONString());

        return jhTmAccountMapper.insert(jhTmAccount);
    }

    /**
     * 修改天猫账户
     *
     * @param jhTmAccount 天猫账户
     * @return 结果
     */
    @Override
    public int updateJhTmAccount(JhTmAccount jhTmAccount) {
        return jhTmAccountMapper.updateJhTmAccount(jhTmAccount);
    }

    /**
     * 批量删除天猫账户
     *
     * @param jhIds 需要删除的天猫账户主键
     * @return 结果
     */
    @Override
    public int deleteJhTmAccountByJhIds(Long[] jhIds) {
        for (Long jhId : jhIds) {
            String feature = getJhFeatureByJhId(jhId);
            if (StringUtils.isNotBlank(feature)) {
                redisCache.deleteObject(feature);
            }
        }
        return jhTmAccountMapper.deleteJhTmAccountByJhIds(jhIds);
    }

    /**
     * 删除天猫账户信息
     *
     * @param jhId 天猫账户主键
     * @return 结果
     */
    @Override
    public int deleteJhTmAccountByJhId(Long jhId) {
        String feature = getJhFeatureByJhId(jhId);
        if (StringUtils.isNotBlank(feature)) {
            redisCache.deleteObject(feature);
        }
        return jhTmAccountMapper.deleteJhTmAccountByJhId(jhId);
    }
    public String getJhFeatureByJhId(Long jhId) {
        LambdaQueryWrapper<JhTmAccount> wrapper = new LambdaQueryWrapper<JhTmAccount>().eq(JhTmAccount::getJhId, jhId);
        JhTmAccount jhTmAccount = jhTmAccountMapper.selectOne(wrapper);
        return jhTmAccount.getJhFeature();
    }

    /**
     * 更新天猫账户配置
     * 只更新 每日每店复制数量;上架设置;检测重复
     *
     * @param jhTmAccount 天猫账户
     * @return 结果
     */
    @Override
    public int updateJhTmAccountConfig(JhTmAccount jhTmAccount) {
        return jhTmAccountMapper.updateJhTmAccountConfig(jhTmAccount);
    }

    @Override
    @Transactional
    public int transferTraffic(Long jhId, Long originalId) {
        // 暂不校验
        JhTmAccount originalAccount = jhTmAccountMapper.selectJhTmAccountByJhId(originalId);
        JhTmAccount jhTmAccount = jhTmAccountMapper.selectJhTmAccountByJhId(jhId);
        log.info("用户 {} 开始转移流量, 原始店铺为 {} ，将 {} 流量转移到 {}",
                SecurityUtils.getUsername(), originalAccount.getJhName(), originalAccount.getJhTrafficNum(), jhTmAccount.getJhName());
        jhTmAccount.setJhTrafficNum(originalAccount.getJhTrafficNum() + jhTmAccount.getJhTrafficNum());
        originalAccount.setJhTrafficNum(0);
        try {
            jhTmAccountMapper.updateById(originalAccount);
            jhTmAccountMapper.updateById(jhTmAccount);
            return 1;
        } catch (Exception e) {
            log.error("流量转移失败", e);
            return 0;
        }
    }

    /**
     * 检查授权状态，如果授权成功则保存品牌id
     *
     * @param jhId
     * @return
     */
    @Override
    public boolean checkAuthorization(Long jhId) {
        JhTmAccount jhTmAccount = jhTmAccountMapper.selectJhTmAccountByJhId(jhId);
        if (jhTmAccount==null || jhTmAccount.getJhAppSession()==null){
            throw new RuntimeException("未获取到店铺授权信息(sessionKey/accessToken)");
        }
        JSONObject itemsAuthorized = null;
        try {
            itemsAuthorized = callTaoApiService.getItemsAuthorized(jhTmAccount);
        } catch (ServiceException e) {
            log.error(e.getMessage(), e);
            return false;
        }

        if(itemsAuthorized != null){
            JSONArray brands = itemsAuthorized.getJSONArray("brands");
            if (brands.size() == 1) {
                jhTmAccount.setJhStatus("1");
                jhTmAccount.setJhBrand(brands.getJSONObject(0).getString("vale"));
                jhTmAccountMapper.updateJhTmAccount(jhTmAccount);
                return true;
            }else{
                // 暂时没有遇到其他场景，如果报错就需要修改代码
                throw new RuntimeException("多个品牌情况出现，需要尽快修复代码");
            }
        }else{
            throw new RuntimeException("查询商家被授权品牌列表和类目列表,异常！！！");
        }

    }

    @Override
    public Long updateSessionKeyByName(String decodedNick, String accessToken) {
        JhTmAccount account = null;
        try {
            account = jhTmAccountMapper.selectOne(
                    new LambdaQueryWrapper<JhTmAccount>()
                            .eq(JhTmAccount::getJhName, decodedNick)
            );
        }catch (Exception e){
            throw new RuntimeException("店铺查询异常:或存在多个名为[" + decodedNick + "]的店铺");
        }
        if (account == null) {
            throw new RuntimeException("根据名称未查询到店铺账户信息,无法更新sessionKey");
        }
        account.setJhAppSession(accessToken);
        jhTmAccountMapper.updateById(account);
        return account.getJhId();
    }
}
